package com.example.administrator.base.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.R;
import com.example.administrator.base.util.IdCardCheckUtil;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import okhttp3.Response;

public class Regiest extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {

    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.et_name)
    EditText etName;
    @InjectView(R.id.et_idcard)
    EditText etIdcard;
    @InjectView(R.id.et_phone)
    EditText etPhone;
    @InjectView(R.id.et_password)
    EditText etPassword;
    @InjectView(R.id.ib_sfz)
    ImageButton ibSfz;
    @InjectView(R.id.ib_sfzz)
    ImageButton ibSfzz;
    SweetAlertDialog sweetAlertDialogchoose, sweetAlertDialog;
    @InjectView(R.id.rl_image)
    RelativeLayout rlImage;
    @InjectView(R.id.iv_photo)
    ImageView ivPhoto;
    private TakePhoto takePhoto;
    private Uri tempUri;
    private InvokeParam invokeParam;
    List<String> filepath;
    String path;
    String ib = "";
    Bitmap bm, bmx;
    CropOptions cropOptions;
    boolean isshow = false;
    boolean isshowx=false;
    int photonumber=0;
    String name="";
    String id="";
    String phone="";
    String password="";
    final String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    // 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
    final OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAII0PG5gwizO08", "FemIHua5m8s7pM43abyKlbPK5Lm1h3");
    OSS oss;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regiest);
        ButterKnife.inject(this);
        getTakePhoto().onCreate(savedInstanceState);
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
        filepath = new ArrayList<>();
        String path = Environment.getExternalStorageDirectory() + "/JJDC/image/head+" + System.currentTimeMillis() + ".jpg";
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            boolean mkdirs = file.getParentFile().mkdirs();
            Log.i("1",""+mkdirs);
        }
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
        tempUri = Uri.fromFile(file);
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("注册");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);

    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    @OnClick({R.id.btn_next2, R.id.ib_sfz, R.id.ib_sfzz})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next2:
                 name = etName.getText().toString();
                 id = etIdcard.getText().toString();
                 phone = etPhone.getText().toString();
                 password = etPassword.getText().toString();
                if (name.equals("")) {
                    showToast("请输入姓名");
                    return;
                }
                if (id.equals("")) {
                    showToast("请输入身份证号");
                    return;
                }
                if (phone.equals("")) {
                    showToast("请输入手机号");
                    return;
                }
                if (password.equals("")) {
                    showToast("请输入密码");
                    return;
                }
                if (!IdCardCheckUtil.checkIDCard(id)){
                    showToast("身份证不正确");
                    return;
                }
                if (!IdCardCheckUtil.isMobile(phone)){
                    showToast("手机号不正确");
                    return;
                }
                if (filepath.size() != 2) {
                    showToast("请先选择照片");
                } else {
                    sweetAlertDialog.setTitleText("上传中");
                    sweetAlertDialog.show();
                    for (int x = 0; x < filepath.size(); x++) {
                        Log.i("12395681","for循环");
                        String time = "" + name + phone + String.valueOf(System.currentTimeMillis());
                        UploadImg(filepath.get(x), time + ".jpg");
                    }
                }
                break;


            case R.id.ib_sfz:
                ib = "sfz";
                if (isshow) {
                    rlImage.setVisibility(View.VISIBLE);
                    ivPhoto.setImageBitmap(bm);
                } else {
                    sweetAlertDialogchoose = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
                    sweetAlertDialogchoose.setCanceledOnTouchOutside(true);
                    sweetAlertDialogchoose
                            .setTitleText("请选择拍照或从相册中获取")
                            .setContentText("如果您的相册中已有相关照片，请直接从相册获取")
                            .setConfirmText("拍照")
                            .setCancelText("从相册获取")
                            .showCancelButton(true)
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    getTakePhoto().onPickFromCapture(tempUri);
                                    sDialog.dismiss();
                                }
                            })
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    getTakePhoto().onPickFromGalleryWithCrop(tempUri, cropOptions);
                                    sweetAlertDialog.dismiss();
                                }
                            })
                            .show();
                }
                break;
            case R.id.ib_sfzz:
                ib = "sfzz";
                if (isshowx) {
                    rlImage.setVisibility(View.VISIBLE);
                    ivPhoto.setImageBitmap(bmx);
                } else {
                    sweetAlertDialogchoose = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
                    sweetAlertDialogchoose.setCanceledOnTouchOutside(true);
                    sweetAlertDialogchoose
                            .setTitleText("请选择拍照或从相册中获取")
                            .setContentText("如果您的相册中已有相关照片，请直接从相册获取")
                            .setConfirmText("拍照")
                            .setCancelText("从相册获取")
                            .showCancelButton(true)
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    getTakePhoto().onPickFromCapture(tempUri);
                                    sDialog.dismiss();
                                }
                            })
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    getTakePhoto().onPickFromGalleryWithCrop(tempUri, cropOptions);
                                    sweetAlertDialog.dismiss();
                                }
                            })
                            .show();
                }
                break;
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        TImage image = result.getImage();
        String path = image.getOriginalPath();
        Log.i("3378", "path = " + path);
        if (ib.equals("sfz")) {
            isshow = true;
        } else if (ib.equals("sfzz")) {
            isshowx = true;
        }
        luban(path);
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }


    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    private void luban(final String imgPath) {

        File file = new File(imgPath);
        Luban.compress(this, file)
                .putGear(Luban.THIRD_GEAR)
                .launch(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        sweetAlertDialog.setTitleText("压缩中。。。");
                        sweetAlertDialog.show();
                    }

                    @Override
                    public void onSuccess(final File file) {
                        sweetAlertDialog.dismiss();
                        Log.i("3378", "压缩后路径:" + file.getPath());
                        path = file.getPath();
                        filepath.add(path);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("压缩成功");
                                if (ib.equals("sfz")) {
                                    bm = BitmapFactory.decodeFile(file.getPath());
                                    ibSfz.setImageBitmap(bm);
                                } else if (ib.equals("sfzz")) {
                                    bmx = BitmapFactory.decodeFile(file.getPath());
                                    ibSfzz.setImageBitmap(bmx);
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("压缩失败");
                        sweetAlertDialog.dismiss();
                        Log.e("3378", "图片压缩失败" + e.toString());
                    }
                });
    }

    public void UploadImg(String picPath, String objact) {

        PutObjectRequest put = new PutObjectRequest("jjdc", "adminstrator/" + objact, picPath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });
        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        photonumber++;
                        if (photonumber==2){
                            sweetAlertDialog.dismiss();
                            showToast("上传成功");
                            Intent intent=new Intent(Regiest.this,RegiestTwo.class);
                            intent.putExtra("name",name);
                            intent.putExtra("id",id);
                            intent.putExtra("phone",phone);
                            intent.putExtra("password",password);
                            startActivity(intent);

                        }
                        Log.i("12395681","上传完成"+photonumber);
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {

                if (clientExcepion != null) {
                    Log.i("3378", clientExcepion.getMessage());
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.i("3378", serviceException.getErrorCode());
                    Log.i("3378", serviceException.getRequestId());
                    Log.i("3378", serviceException.getHostId());
                    Log.i("3378", serviceException.getRawMessage());
                }

            }
        });
    }


    @OnClick(R.id.ib_cancel)
    public void onViewClicked() {
        rlImage.setVisibility(View.GONE);
    }
}
